package com.water.smartfarm.main;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.water.smartfarm.R;
import com.water.smartfarm.tools.Const;
import com.water.smartfarm.tools.DATEHelper;

import java.text.SimpleDateFormat;
import java.util.Date;


public class MainFragment extends Fragment implements View.OnClickListener {
    private View mRootView = null;

    private TextView tempText;
    private TextView tempStatus;
    private TextView humidityText;
    private TextView humidityStatus;
    private TextView lightText;
    private TextView lightStatus;
    private TextView co2Text;
    private TextView co2Status;
    private Button link;
    private Button refresh;

    String temp;
    String humidyty;
    String light;
    String co2;
    String time;

    DATEHelper dbHelper;
    SQLiteDatabase db;

    String upTemp;
    String downTemp;
    String upHum;
    String downHum;
    String upLight;
    String downLight;
    String upCo2;
    String downCo2;

    String notifiy;
    private String notifiyTemp;
    private String notifiyHum;
    private String notifiyLight;
    private String notifiyCO2;

    private void initView() {
        tempText = (TextView) mRootView.findViewById(R.id.temp_text);
        tempStatus = (TextView) mRootView.findViewById(R.id.temp_status);
        humidityText = (TextView) mRootView.findViewById(R.id.humidity_text);
        humidityStatus = (TextView) mRootView.findViewById(R.id.humidity_status);
        lightText = (TextView) mRootView.findViewById(R.id.light_text);
        lightStatus = (TextView) mRootView.findViewById(R.id.light_status);
        co2Text = (TextView) mRootView.findViewById(R.id.co2_text);
        co2Status = (TextView) mRootView.findViewById(R.id.co2_status);
        link = (Button) mRootView.findViewById(R.id.link);
        link.setOnClickListener(this);
        refresh = (Button) mRootView.findViewById(R.id.refresh);
        refresh.setOnClickListener(this);

        initDateBase();
        refresh();
    }

    private void initDateBase() {
        dbHelper = new DATEHelper(getActivity(), Const.DATA);
        db = dbHelper.getWritableDatabase();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_main, container, false);
        initView();
        return mRootView;
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.link:
                linkDialog();
                break;
            case R.id.refresh:
                refresh();
                break;
        }
    }

    private void refresh() {
        changeData();

        saveData();

        getSPData();

        notifiyTemp = changeNotify(temp, upTemp, downTemp, "温度");
        notifiyHum = changeNotify(humidyty, upHum, downHum, "湿度");
        notifiyLight = changeNotify(light, upLight, downLight, "光强度");
        notifiyCO2 = changeNotify(co2, upCo2, downCo2, "CO2");

        notifiy = notifiyTemp + notifiyHum + notifiyLight + notifiyCO2;
        if (!TextUtils.isEmpty(notifiy)) {
            notifiMsg();
        }
    }

    private void notifiMsg() {
        NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 0,
                new Intent(getActivity(), MainActivity.class), 0);


        // 通过Notification.Builder来创建通知，注意API Level
        // API11之后才支持
        Notification notify = new Notification.Builder(getActivity())
                .setSmallIcon(R.drawable.main_icon_personal) // 设置状态栏中的小图片，尺寸一般建议在24×24，这个图片同样也是在下拉状态栏中所显示，如果在那里需要更换更大的图片，可以使用setLargeIcon(Bitmap
                        // icon)
                .setTicker(notifiy)// 设置在status
                        // bar上显示的提示文字
                .setContentTitle("警告")// 设置在下拉status
                        // bar后Activity，本例子中的NotififyMessage的TextView中显示的标题
                .setContentText(notifiy)// TextView中显示的详细内容
                .setContentIntent(pendingIntent) // 关联PendingIntent
                .setNumber(1) // 在TextView的右方显示的数字，可放大图片看，在最右侧。这个number同时也起到一个序列号的左右，如果多个触发多个通知（同一ID），可以指定显示哪一个。
                .getNotification(); // 需要注意build()是在API level
        // 16及之后增加的，在API11中可以使用getNotificatin()来代替
        notify.flags |= Notification.FLAG_AUTO_CANCEL;
        manager.notify(1, notify);
    }

    private void saveData() {
        time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        ContentValues values = new ContentValues();
        values.put("temp", temp);
        values.put("humid", humidyty);
        values.put("light", light);
        values.put("level", temp);
        values.put("CO2", co2);
        values.put("time", time);
        //调用方法插入数据
        db.insert(Const.DATA, "id", values);
        values.clear();
    }

    private void changeData() {
        float tempNum = (float) (Math.random() * 7 + 10);
        temp = (tempNum + "").substring(0, 5);
        tempText.setText(temp);
        float humidNum = (float) (Math.random() * 8 + 10);
        humidyty = (humidNum + "").substring(0, 5);
        humidityText.setText(humidyty);
        float ligntNum = (float) (Math.random() * 9 + 10);
        light = (ligntNum + "").substring(0, 5);
        lightText.setText(light);
        float co2Num = (float) (Math.random() * 12 + 10);
        co2 = (co2Num + "").substring(0, 5);
        co2Text.setText(co2);
        changeState(tempNum, 10.0f, 20.0f, tempStatus);
        changeState(humidNum, 10.0f, 20.0f, humidityStatus);
        changeState(ligntNum, 10.0f, 20.0f, lightStatus);
        changeState(co2Num, 10.0f, 20.0f, co2Status);
        humidityText.setText(humidyty);
        lightText.setText(light);
        co2Text.setText(co2);
    }

    public String changeNotify(String temp, String up, String down, String type) {
        if (!TextUtils.isEmpty(temp) && !TextUtils.isEmpty(up) && !TextUtils.isEmpty(down) && !TextUtils.isEmpty(type)) {
            if (Float.parseFloat(up) < Float.parseFloat(temp)) {
                notifiy = type + "过高";
            } else if (Float.parseFloat(down) > Float.parseFloat(temp)) {
                notifiy = type + "过低";
            } else {
                notifiy = "";
            }
        } else {
            notifiy = "";
        }
        return notifiy;
    }

    private void getSPData() {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("data",
                Activity.MODE_PRIVATE);
        // 使用getString方法获得value，注意第2个参数是value的默认值
        upTemp = sharedPreferences.getString(Const.up_temp, upTemp);
        downTemp = sharedPreferences.getString(Const.down_temp, downTemp);
        upHum = sharedPreferences.getString(Const.up_hum, upHum);
        downHum = sharedPreferences.getString(Const.down_hum, downHum);
        upLight = sharedPreferences.getString(Const.up_light, upLight);
        downLight = sharedPreferences.getString(Const.down_light, downLight);
        upCo2 = sharedPreferences.getString(Const.up_co2, upCo2);
        downCo2 = sharedPreferences.getString(Const.down_co2, downCo2);
    }

    private void changeState(float tempNum, float down, float up, TextView status) {
        if (tempNum > up) {
            status.setText(R.string.high);
        } else if (tempNum < down) {
            status.setText(R.string.low);
        } else {
            status.setText(R.string.mid);
        }
    }

    private void linkDialog() {
        final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.link_dialog);
        Button confim_btn = (Button) window.findViewById(R.id.confim_btn);
        confim_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                alertDialog.cancel();
                Toast.makeText(getActivity(), "连接成功",
                        Toast.LENGTH_SHORT).show();
            }
        });
        Button cancel_btn = (Button) window.findViewById(R.id.cancel_btn);
        cancel_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                alertDialog.cancel();

            }
        });

    }
}
